import { createTask as createTask2, deleteTaskCenterRecord, getTaskCenterRecordList } from '@/api/taskCenter'
import router from '@/router'
import * as taskCodes from '@/contracts/taskCodes'
import { ElMessage as $message, ElMessageBox as $messageBox } from 'element-plus'

/**
 * 解析确认框参数
 * @param {*} options 参数
 * @returns 返回确认框参数
 */
const resolveConfimOptions = (options) => {
  let confimOptions = undefined
  let m = options.confirm || options.Confirm

  if (m && typeof m === 'string') {
    m = { message: m }
  }

  if (m && typeof m == 'object' && m.message && typeof m.message == 'string') {
    confimOptions = Object.assign({ title: '提示', type: 'warning' }, m)
  }

  return confimOptions
}

/**
 * 获取菜单路径
 * @returns
 */
const getMenuPath = () => {
  return (
    router.currentRoute.value.matched
      .map((r) => (r.meta || {}).title)
      .filter((a) => !!a)
      .join('>') || '销售系统'
  )
}

let createTask = (options) => {
  options = options || {}
  let taskCode = options.taskCode || options.taskCenterType

  if (!taskCode) {
    console.error('taskCode undefined !')
    $message.error('缺少创建任务必要参数：actionKey，请联系管理员处理！')
    return
  }

  // 处理确认框选项
  let confimOptions = resolveConfimOptions(options)

  // 处理 请求参数
  let parameters = Object.assign({ __standard: true }, options.parameters || {})

  function handleOptionValue() {
    let names = [...arguments]
    if (!names || names.length == 0) return

    let value = undefined
    let hasValue = false
    var arr = [options, parameters]
    for (let i = 0; i < arr.length; i++) {
      for (let j = 0; j < names.length; j++) {
        value = arr[i][names[j]]
        hasValue = value !== undefined && value !== null
        if (hasValue) break
      }
      if (hasValue) break
    }

    names.forEach((n) => {
      delete parameters[n]
    })
    if (hasValue) parameters[names[0]] = value
  }

  handleOptionValue('requestFilter', 'RequestFilter')
  handleOptionValue('requestParams', 'RequestParams')
  handleOptionValue('params', 'Params')

  parameters.__standard = true //标记字段，用于后端识别

  let data = {
    taskCode: taskCode,
    menuPath: options.menuPath || options.MenuPath || getMenuPath(),
    category: options.taskCategory,
    extraParameters: parameters,
  }

  let p = new Promise((resolve, reject) => {
    let doRequest = () => {
      createTask2(data)
        .then((res) => {
          if (!res || !res.isSuccess) {
            $message.error(res.message || '服务异常')
            return
          }
          let tip = options.successTip || options.successTip
          if (tip !== false) {
            let successTip = tip || '操作成功，请在任务中心查看进度！'
            $message.success(successTip)
          }
          resolve({ taskId: res.data })
        })
        .catch(reject)
    }

    if (confimOptions && confimOptions.message) {
      $messageBox
        .confirm(confimOptions.message, confimOptions)
        .then(doRequest)
        .catch(() => false)
    } else {
      doRequest()
    }
  })

  return p
}

/**
 * 删除任务记录
 * @param {*} options 参数
 * @returns
 */
let deleteTask = (options) => {
  let type = typeof options
  if (type === 'string' || type === 'number') {
    let taskId = options
    options = { taskId: taskId }
  } else if (type !== 'object') return

  let taskId = options.taskId

  // 处理确认框选项
  let confimOptions =
    options.confirm === false
      ? undefined
      : resolveConfimOptions(options) || {
          title: '提示',
          type: 'warning',
          message: '此操作将永久删除该记录, 是否继续?',
        }

  let p = new Promise((resolve, reject) => {
    let doRequest = () => {
      deleteTaskCenterRecord({
        taskCenterRecordId: taskId,
      })
        .then((res) => {
          if (!res || !res.isSuccess) {
            $message.error(res.message || '服务异常')
            return
          }
          let tip = options.successTip || options.successTip
          if (tip !== false) {
            let successTip = tip || '任务记录删除成功！'
            $message.success(successTip)
          }
          resolve(res)
        })
        .catch(reject)
    }

    if (confimOptions && confimOptions.message) {
      $messageBox
        .confirm(confimOptions.message, confimOptions)
        .then(doRequest)
        .catch(() => false)
    } else {
      doRequest()
    }
  })

  return p
}

/**
 * 分页获取任务记录
 * @param {*} options 请求参数
 */
let getTaskPagingList = (options = {}) => {
  var params = Object.assign(
    {
      pageIndex: 0,
      pageSize: 50,
      sortName: 'ID',
      sortOrder: 'desc',
    },
    options,
  )

  let p = new Promise((resolve, reject) => {
    getTaskCenterRecordList(params)
      .then((res) => {
        // if (res && res.isSuccess && res.data.data.length > 0) {
        //   res.data.data.forEach((element) => {
        //     fillTaskActionInfo(element)
        //   })
        // }
        resolve(res)
      })
      .catch(reject)
  })

  return p
}

let taskCenter = {
  taskCodes,
  createTask,
  deleteTask,
  getTaskPagingList,
}
taskCenter.install = (app) => {
  app.provide('taskProvide', taskCenter)
}

export default taskCenter
